# -*- coding: utf-8 -*-
# @Time : 2023/11/22 11:55
# @Author : ZH
# @File : mapcoordinates.py
# @Software: PyCharm
import requests


class MapCoordInates:
    def __init__(self, proxies: dict, **kwargs):
        """

        :param proxies: 代理
            proxies = {
                'http': 'http://127.0.0.1:7890',
                'https': 'http://127.0.0.1:7890'
                }
        """
        self.proxies = proxies

    @classmethod
    def get_support(cls):
        support = ['cn', 'en']
        return support

    def start_main(self, location: str, limit=5, timeout=10, **kwargs):
        headers = {
            'authority': 'nominatim.openstreetmap.org',
            'accept': '*/*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'no-cache',
            'pragma': 'no-cache',
            'referer': 'https://nominatim.openstreetmap.org/ui/search.html?q=%E5%8C%97%E4%BA%AC',
            'sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-origin',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
        }
        params = {
            'q': location,
            'polygon_geojson': '1',
            'format': 'jsonv2',
        }
        for i in range(3):
            try:
                # response = requests.get('https://nominatim.openstreetmap.org/search', params=params, headers=headers,
                #                         proxies=self.proxies)
                response = requests.get('https://nominatim.openstreetmap.org/search.php', params=params,
                                        headers=headers,timeout=timeout,
                                        proxies=self.proxies)
                # all_data = json.loads(response.text.replace('L.Control.Search.callJsonp(', '')[:-1])
                all_data = response.json()
                return [
                    {"lat": data.get('lat'), "lon": data.get('lon'), 'country': '', "name": data.get('display_name')}
                    for data in all_data]
            except:
                pass

        return None

